package com.sbhotel.chotellauncher;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.gson.Gson;
import com.sbhotel.chotellauncher.constant.Constants;
import com.sbhotel.chotellauncher.entity.LauncherMainMenuBean;
import com.sbhotel.chotellauncher.util.LauncherConfigUtil;
import com.sbhotel.chotellauncher.util.SPUtil;
import com.sbhotel.chotellauncher.util.Utils;
import com.sbhotel.chotellauncher.widget.PowerOffDialog;

import java.io.File;

public class MyReceiver extends BroadcastReceiver {

    private static final String ACTION_SHUTDOWN = "android.intent.action.ACTION_SHUTDOWN";
    private static final int HOME_KEY_CODE = 4124;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Constants.ACTION_POWER_OFF.equals(action)) {
            //Utils.shutDownDevice(context);
            //SPUtil.put(context, Constants.SP_KEY_SLEEP_VALUE, "");
            new PowerOffDialog(context).show();
        } else if (ACTION_SHUTDOWN.equals(action)) {
            SPUtil.put(context, Constants.SP_KEY_SLEEP_VALUE, "");
        } else if (Constants.ACTION_HOME_KEY.equals(action)) {

            int keycode = intent.getIntExtra(Intent.EXTRA_KEY_EVENT, -1);
            //Log.d(Constants.LOG_TAG, "keycode = " + keycode);
            if (keycode == HOME_KEY_CODE) {
                boolean netError = (boolean) SPUtil.get(context, Constants.SP_KEY_NET_ERROR, false);
                Log.d("leihuiming", "HOME_KEY_CODE netError = " + netError);
                if(netError) {
                    return;
                }
                if(MyApplication.disableHomeKey) return;
                Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
                launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                launcherIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(launcherIntent);
            }
        } else if(Constants.ACTION_UPGRADE.equals(action)) {
            MyApplication.disableHomeKey = intent.getBooleanExtra("disableHomeKey", false);
            Log.d(Constants.LOG_TAG, "MyApplication.disableHomeKey = " + MyApplication.disableHomeKey);
        } else if(Constants.ACTION_CONFIG_OK.equals(action)) {
            Log.d(Constants.LOG_TAG, "ACTION_CONFIG_OK");
            String config = LauncherConfigUtil.readFileData(context, Constants.CONFIG_FILE_PATH);
            LauncherConfigUtil.writeFileData(context, Constants.CONFIG_FILE_OK_PATH, config);
            File file = new File(Constants.CONFIG_FILE_PATH);
            file.delete();
            LauncherMainMenuBean bean = new Gson().fromJson(config, LauncherMainMenuBean.class);
            SPUtil.put(context, Constants.SP_KEY_CURRENT_CONF_VERSION, bean.getData().getConf_version());
        }
    }
}